<template>
  <!-- 动火安全作业票申请 -->
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="ticketForm" :rules="rules" labelPosition="top">
        <view class="hidden-title">信息填写</view>
        <cu-cell-group>
          <uni-forms-item name="workLevel">
            <cu-cell class="cu-cell--select-v2" title="动火作业级别" required>
              <CuSelectV2
                v-model="ticketForm.workLevel"
                title="动火作业级别"
                placeholder="请选择"
                label-key="title"
                value-key="level"
                :options="workTypeOptions"
                @change="onTicketWorkTypeLevelChange"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item name="workLocation">
            <cu-cell title="动火地点" required>
              <input
                type="text"
                v-model="ticketForm.workLocation"
                placeholder="请输入(限20字)"
                class="input"
                placeholder-class="input-placeholder"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>
        </cu-cell-group>
        <view class="other-work-pattern">
          <uni-forms-item name="checkList" label="动火方式（可多选）" labelWidth="150" required>
            <cu-select v-model="ticketForm.checkList" :list="checkList"></cu-select>
            <view v-if="inputOn" class="other-type">
              <input
                type="text"
                v-model="ticketForm.otherWorkPattern"
                class="input"
                placeholder="请填写其他动火方式"
                placeholder-class="input-placeholder"
                maxlength="6"
              />
            </view>
          </uni-forms-item>
        </view>
        <cu-cell-group>
          <uni-forms-item name="libId">
            <hazardous-medium-select v-model="ticketForm.libId" label="危害介质" placeholder="请选择" required />
          </uni-forms-item>
        </cu-cell-group>

        <cu-cell-group>
          <uni-forms-item name="startTime">
            <uni-datetime-picker
              hide-second
              :start="now"
              :end="endTime"
              type="datetime"
              @change="onTimeChange($event, 'startTime')"
            >
              <cu-cell
                title="动火开始时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.startTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
          <uni-forms-item name="endTime">
            <uni-datetime-picker
              hide-second
              :start="startTime"
              type="datetime"
              @change="onTimeChange($event, 'endTime')"
            >
              <cu-cell
                title="动火结束时间"
                required
                link
                placeholder="请选择"
                :description="ticketForm.endTime"
              ></cu-cell>
            </uni-datetime-picker>
          </uni-forms-item>
          <uni-forms-item name="principal">
            <cu-cell
              title="动火作业负责人"
              required
              link
              placeholder="请选择"
              :description="ticketForm.principalLabel"
              @click="showUserSelector('principal')"
            ></cu-cell>
          </uni-forms-item>
          <uni-forms-item name="workCertificatesConfirm">
            <cu-cell
              title="动火人"
              required
              link
              placeholder="请选择"
              :description="ticketForm.workCertificatesConfirm"
              @click="showUserSelector('workCertificates')"
            ></cu-cell>
            <uni-forms-item name="workCertificates" label="">
              <div
                v-for="(item, index) in ticketForm.workCertificates"
                :key="index"
                style="display: inline-flex; justify-content: space-between; align-items: center; width: 95%"
              >
                <div class="index">{{ index + 1 }}</div>
                <div class="name">{{ item.name }}</div>
                <div class="content">
                  <cu-cell
                    title=""
                    link
                    placeholder="请选择"
                    :description="item.qualityName"
                    @click="selectCertificate(item.quality)"
                  ></cu-cell>
                </div>
                <div class="operate">
                  <span @click="removeCertificates(index)">移除</span>
                </div>
              </div>
            </uni-forms-item>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>
    </view>

    <!-- 用户选择器 v2 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :checkList="deptUserSelectProps.checkList"
      :auto-request-user="deptUserSelectProps.autoRequestUser"
      :dept-id="unitId"
      :multiple="deptUserSelectProps.multiple"
      @change="onDeptUserChange"
    ></cu-dept-user-select>

    <!--动火人证书-->
    <data-picker
      ref="qualityRef"
      title=""
      label-key="qualityName"
      value-key="qualityId"
      :data="qualities"
      @confirm="qualityConfirm"
    ></data-picker>
  </view>
</template>

<script>
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellMultiLine from '@/components/cu-cell/cu-cell-multi-line.vue'
import CuSelect from '@/components/cu-select/cu-select.vue'
import CuSelectV2 from '@/components/cu-select-v2/cu-select-v2.vue'
import DataPicker from '@/components/data-picker/index.vue'
import HazardousMediumSelect from '@/components/hazardous-medium-select/hazardous-medium-select.vue'

import dayjs from 'dayjs'
import { getQualificationInfo, queryTicketWorkTypeLevel } from '../../../api/spw/ticketApply'
import { specialWorkTypeEnum } from '@/utils/constant'
import { cloneDeep } from 'lodash'

const workPatterns = {
  1: '电焊',
  2: '气焊',
  3: '切割',
  4: '砂轮',
  5: '电钻',
  6: '喷灯',
  7: '液化气炉',
  8: '电锤',
  99: '其他'
}

export default {
  components: {
    CuCellGroup,
    CuCell,
    CuCellMultiLine,
    CuSelect,
    CuSelectV2,
    CuDeptUserSelect,
    DataPicker,
    HazardousMediumSelect
  },
  computed: {
    inputOn() {
      return this.ticketForm.checkList.includes('99')
    },
    endTime() {
      if (!this.ticketForm.endTime) {
        return ''
      }
      return dayjs(this.ticketForm.endTime).valueOf() - 60 * 60 * 1000
    },
    startTime() {
      if (!this.ticketForm.startTime) {
        return ''
      }
      return dayjs(this.ticketForm.startTime).valueOf() + 60 * 60 * 1000
    }
  },
  mounted() {
    this.getTicketWorkTypeLevel()
    this.checkList = Object.keys(workPatterns).map((item) => {
      return {
        lable: workPatterns[item],
        value: String(item)
      }
    })
  },
  props: {
    ticketInfo: {
      type: Object,
      default: () => {}
    },
    nodeList: {
      type: Array,
      default: () => []
    },
    templateId: {
      type: [String, Number],
      default: ''
    },
    unitId: {
      type: [String, Number],
      default: ''
    },
    procDefId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    const validatorLib = (rule, value, data, callback) => {
      if (value.length) {
        return true
      } else {
        return callback('不能为空')
      }
    }
    return {
      deptUserSelectProps: {
        checkList: [],
        multiple: false,
        autoRequestUser: true
      },
      workTypeOptions: [],
      template: {},
      ticketForm: {
        workLocation: '',
        startTime: '',
        endTime: '',
        checkList: [], // 作业方式
        libId: [], // 危害介质
        otherWorkPattern: '', // 其他动火作业方式
        workLevel: '', // 作业级别
        workLevelLabel: '', // 作业级别
        principal: '', // 作业负责人
        principalLabel: '',
        workCertificatesConfirm: '',
        workCertificates: []
      },
      selectUserType: 1,
      nodeIdx: '',
      checkList: [],
      qualities: [],
      result: {},
      staffs: [],
      upgradeUserList: [],
      now: dayjs(new Date()).format('YYYY-MM-DD HH:mm'),
      rules: {
        libId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            },
            {
              validateFunction: validatorLib
            }
          ]
        },
        startTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        endTime: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        checkList: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workLevel: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        principal: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workCertificatesConfirm: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  watch: {
    ticketInfo: {
      async handler(val) {
        if (val) {
          Object.keys(this.ticketInfo).map((k) => {
            this.ticketForm[k] = cloneDeep(val[k])
          })
        }
      },
      immediate: true
    },
    unitId: {
      handler(nv, ov) {
        if (!ov) return
        this.ticketForm.principalLabel = ''
        this.ticketForm.workCertificatesConfirm = ''
        this.ticketForm.workCertificates = []
      }
    }
  },
  methods: {
    onDeptUserChange(val) {
      if (!val) {
        return
      }

      switch (this.selectUserType) {
        case 'workCertificates':
          this.setQualification(val)
          break
        case 'principal':
          this.ticketForm.principal = val[0].userId
          this.ticketForm.principalLabel = val[0].name
          break
        default:
          break
      }
    },
    onTicketWorkTypeLevelChange(val) {
      this.ticketForm.workLevelLabel = val.title
      this.$emit('on-level-change', val.level)
    },
    getTicketWorkTypeLevel() {
      queryTicketWorkTypeLevel(specialWorkTypeEnum.FIRE).then((res) => {
        this.workTypeOptions = res.data
      })
    },
    showUserSelector(type) {
      this.selectUserType = type

      switch (type) {
        case 'workCertificates':
          if (!this.unitId) {
            this.$modal.showToast('请先选择作业单位')
            return
          }
          this.deptUserSelectProps.checkList = []
          this.deptUserSelectProps.multiple = true
          break
        case 'principal':
          if (!this.unitId) {
            this.$modal.showToast('请先选择作业单位')
            return
          }
          this.deptUserSelectProps.checkList = this.ticketForm.principal
            ? [{ userId: this.ticketForm.principal, name: this.ticketForm.principalLabel }]
            : []
          this.deptUserSelectProps.multiple = false
          break
        default:
          break
      }
      this.$refs.deptUserSelectRef.open()
    },

    // 动火人[本企业、承包商]
    async setQualification(arr) {
      let api = getQualificationInfo
      const request = []
      const userId = []
      arr.forEach((item) => {
        request.push(api(item.staffId))
        userId.push(item.staffId)
      })
      const res = await Promise.all(request)
      arr.map((item, index) => {
        item.quality = res[index].data
        if (!item.quality.length) return

        item.quality.map((q) => {
          q.text = q.qualityName
          q.value = q.qualityId
        })

        // 默认选中第一个证书
        item.qualityName = item.quality[0].qualityName
        item.qualityId = item.quality[0].qualityId
        item.qualityNumber = item.quality[0].qualityNumber
      })
      console.log('workCertificates', arr)
      this.ticketForm.workCertificates = arr
      this.ticketForm.workCertificatesConfirm = '已确认'
    },
    selectCertificate(data) {
      this.qualities = data
      this.$refs.qualityRef.open()
    },
    qualityConfirm(obj) {
      let idx = this.ticketForm.workCertificates.findIndex((c) => {
        return c.userId === obj.userId
      })

      let quality = JSON.parse(JSON.stringify(this.ticketForm.workCertificates[idx].quality))
      let updateObj = {
        name: obj.userName,
        userId: obj.userId,
        qualityName: obj.qualityName,
        qualityId: obj.qualityId,
        qualityNumber: obj.qualityNumber,
        quality: quality
      }
      this.$set(this.ticketForm.workCertificates, idx, updateObj)
    },
    removeCertificates(idx) {
      this.ticketForm.workCertificates.splice(idx, 1)
      if (!this.ticketForm.workCertificates.length) this.ticketForm.workCertificatesConfirm = ''
    },

    onTimeChange(val, key) {
      if (val.trim().includes(' ')) {
        this.ticketForm[key] = val.trim()
      } else {
        this.$modal.showToast('请选择日期和时间')
      }
    },
    certificateValidate() {
      // 230526 选择电焊、气焊（割），需要限制必须有资质证书，其他类型不做限制
      let items = ['1', '2']
      let b = this.ticketForm.checkList.some((c) => {
        return items.includes(String(c))
      })
      if (b) {
        const names = this.ticketForm.workCertificates.filter((pet) => !pet.qualityId).map((item) => item.name)
        if (names.length > 0) {
          console.log(b, names)
          this.$modal.showToast(`动火人 ${names.join('、')} 请选择证书`)
          return false
        }
      }
      return true
    },
    async submit() {
      await this.$refs.form.validate()

      const start = dayjs(this.ticketForm.startTime).valueOf()
      const end = dayjs(this.ticketForm.endTime).valueOf()
      const oneHour = 60 * 60 * 1000
      if (end - start < oneHour) {
        this.$modal.showToast('开始时间与结束时间间隔必须大于60分钟')
        return
      }

      // 作业方式
      const workPattern = []
      this.ticketForm.checkList.forEach((item) => {
        workPattern.push({
          label: workPatterns[item],
          value: item
        })
      })

      this.result = {
        ...this.ticketForm,
        workPattern,
        procDefId: this.procDefId,
        workType: this.ticketForm.workTypeFlag,
        workId: this.ticketForm.workId,
        ticketWorkLevelKey: 'spw_fire_work_level'
      }

      console.log('this.result', this.result)
    }
  }
}
</script>

<style lang="scss" scoped>
.other-type {
  background: #f5f5f5;
  padding: 20rpx;
  margin-top: 10rpx;
  .input {
    text-align: left;
  }
}
.index {
  width: 15px;
}
.name {
  width: 15%;
}
.content {
  width: 60%;
}
.other-work-pattern {
  position: relative;
  background: #fff;
  box-sizing: border-box;
  padding-left: 30rpx;
  padding-top: 20rpx;
  padding-bottom: 20rpx;
  .uni-forms-item {
    margin-bottom: 0;
  }
  &:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 30rpx;
    right: 0;
    background: #d5d7e3;
    height: 1px;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    -webkit-transform-origin: bottom center;
    transform-origin: bottom center;
  }
}
</style>
